import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';

class FileWatcher {
   File? _targetFile;
  DateTime? _lastModifiedTime;
  Timer? _checkTimer;
  Duration _checkInterval;

  FileWatcher({
    Duration checkInterval = const Duration(seconds: 2),
  }) : _checkInterval = checkInterval;

  // 开始监听
  void startWatching({
    required String filePath,
    required Function() onModified, // 文件修改回调
    required Function(String) onError,
  }) async {
    if (kIsWeb) {
      onError("Web平台不支持");
      return;
    }

    _targetFile = File(filePath);
    if (!await _targetFile!.exists()) {
      onError("文件不存在: $filePath");
      return;
    }

    // 获取初始修改时间
    _lastModifiedTime = await _targetFile!.lastModified();

    // 启动定时检查
    _checkTimer = Timer.periodic(_checkInterval, (timer) async {
      await _checkFileChanges(onModified, onError);
    });
  }

  // 检查文件是否变化
  Future<void> _checkFileChanges(
    Function() onModified,
    Function(String) onError,
  ) async {
    try {
      if (_targetFile == null || !await _targetFile!.exists()) {
        onError("文件已删除");
        stopWatching();
        return;
      }

      final currentModified = await _targetFile!.lastModified();
      if (_lastModifiedTime != null && currentModified != _lastModifiedTime) {
        _lastModifiedTime = currentModified;
        onModified(); // 触发修改回调
      }
    } catch (e) {
      onError("检查失败: $e");
    }
  }

  // 停止监听
  void stopWatching() {
    _checkTimer?.cancel();
    _targetFile = null;
    _lastModifiedTime = null;
  }
}